<?php

/**
 * Description of Offer
 *
 * @author Kam
 */
class Application_Model_DAO_Offer extends My_DAO_Abstract {

    const DB_OFFER = 'Offer';
    const DB_OFFER_ATTRIBUTE = 'OfferAttribute';
    const STEP_KEY = 'step';
    const STEP_LOGIN = 'step-login';
    const STEP_CATEGORY = 1;
    const STEP_TYPE = 2;
    const STEP_FORM = 3;
    const STEP_PHOTO = 4;
    const STEP_PREVIEW = 5;
    const STEP_PAYMENT = 6;
    const STEP_PUBLISH = 7;
    const TYPE_FREE = 'free';
    const TYPE_PAID = 'paid';
    const PHOTOS_FREE_AMOUNT = 2;
    const PHOTOS_PAID_AMOUNT = 4;

    public function getShortOfferList($limit = 5) {
        /* @var $select Zend_Db_Select */
        $select = $this->getDbTable()->selectActiveOffers();
        $select->limit($limit);
        return $select->query()->fetchAll();
    }

    /**
     * 
     * @return Zend_Db_Table_Select
     */
    public function getFullOffers() {
        $select = $this->getDbTable()->select()
                ->from(array('o' => 'offer'), array('offer_code' => 'code', '*'))
                ->joinLeft(array('c' => 'category'), 'o.category_id=c.category_id', array('category_code' => 'code', 'category_admin_active' => 'admin_active', 'parent_id', 'level', 'order_id', 'offer_template_id', 'path', 'name', 'description', 'icon_path', 'meta_desc', 'meta_keyword', 'offer_count'))
                ->joinLeft(array('p' => 'payment'), 'o.offer_id=p.source_id AND p.source_name="offer"', array('*'))
                ->where('c.is_deleted = 0')
                ->order(array('o.offer_id DESC'))
        ;
        return $select;
    }

    public function validatePhotos(Zend_Session_Namespace $bean) {
        $type = $bean->type;
        $photos = $bean->photos;
        $cnt = count($photos);
        $props = My_Utils::getOfferProperties();
        $phLimit = $props[$type][My_Utils::PROP_OFFER_PHOTOS_LIMIT];
        if ($cnt >= $phLimit) {
            return $this->translate('XXX_DAO_OFFER_INVALID_PHOTO_NUMBER_PAID');
        }
        return true;
    }

    public function deactivate($id, $column = 'code') {
        return $this->getDbTable()->update(array('admin_active' => 0), $id, $column);
    }

    public function activate($id, $column = 'code') {
        return $this->getDbTable()->update(array('admin_active' => 1), $id, $column);
    }

    public function update($offerId, array $data) {
        return $this->getDbTable()->update($data, $offerId);
    }

    public function addNew($formData, $data) {
        $props = My_Utils::getOfferProperties();
        $type = $data['type'];
        $date = date(My_Db_Table::DATE_TIME_PATTERN);
        $activeFrom = date(My_Db_Table::DATE_TIME_PATTERN);
        $activeLength = $props[$type][My_Utils::PROP_OFFER_ACTIVE_DAYS];
        $activeTo = date(My_Db_Table::DATE_PATTERN, time() + ($activeLength + 1) * 24 * 60 * 60) . ' 00:00:00';   // do północy następnego dnia

        $offerRecord = array(
            'author_id' => $data['author_id'],
            'category_id' => $data['category_id'],
            'offer_template_id' => $data['offer_template_id'],
            'type' => $data['type'],
            'title' => $formData['title'],
            'intro' => $formData['content'],
            'content' => $formData['content'],
            'active' => isset($data['active']) ? $data['active'] : ($type == self::TYPE_FREE ? 1 : 0),
//            'active' => 1,
            'active_length' => $activeLength,
            'active_from' => $activeFrom,
            'active_to' => $activeTo,
        );

        $this->setSafety($offerRecord, $formData, 'contact_name');
        $this->setSafety($offerRecord, $formData, 'contact_phone');
        $this->setSafety($offerRecord, $formData, 'contact_email');
        $this->setSafety($offerRecord, $formData, 'contact_email_visible_flag');
        $this->setSafety($offerRecord, $formData, 'contact_skype');
        $this->setSafety($offerRecord, $formData, 'contact_gg');

        $offerId = $this->getDbTable()->insert($offerRecord);

        $attrs = $formData;
        unset($attrs['title']);
        unset($attrs['content']);
        unset($attrs['contact']);    //@todo
        // create id attributes
        foreach ($attrs as $key => $val) {
            if (stripos($key, 'otaid_') === false) {
                continue;
            }
            $otaid = str_replace('otaid_', '', $key);
            $row = array(
                'offer_template_attribute_id' => $otaid,
                'offer_id' => $offerId,
                'value' => $val,
            );
            $this->getDbTable(self::DB_OFFER_ATTRIBUTE)->insert($row);
        }

        $offerRecord = $this->getDbTable()->get($offerId);
        return $offerRecord;
    }

    public function getOfferByCode($code) {
        /* @var $select Zend_Db_Select */
        $select = $this->getDbTable()->selectActiveOffers();
        $offer = $select->where('o.code = ?', $code)
                        ->query()->fetch();
        if (empty($offer)) {
            return null;
        }
        $offerId = $offer['offer_id'];
        $tplId = $offer['offer_template_id'];
        $attr = array();
        if (!empty($tplId) && $tplId > 0) {
            $modelOfferTemplate = new Application_Model_DbTable_OfferTemplate();
            $select = $modelOfferTemplate->getTemplateAttributes($tplId);
            $attr = $select->joinLeft(array('oa' => 'offer_attribute'), 'ta.offer_template_attribute_id=oa.offer_template_attribute_id AND oa.offer_id=' . $offerId, array('offer_attribute_id', 'value'))
                            ->query()->fetchAll();
        }
        $offer['attributes'] = $attr;
        $modelImages = new Application_Model_DbTable_Image();
        $images = $modelImages->getBySource('offer', $offerId)
                        ->query()->fetchAll();
        $offer['images'] = $images;
        return $offer;
    }

    /**
     * 
     * @param int $categoryId
     * @param int $page
     * @param int $rowCount
     * @return Zend_Db_Select
     */
    public function getByCategoryId($categoryId) {
        $daoCategory = new Application_Model_DAO_Category();
        $subCategoriesIds = $daoCategory->getSubCategoriesIds($categoryId);

        /* @var $select Zend_Db_Select */
        $select = $this->getDbTable()->selectActiveOffers();
        $select->where('o.category_id IN (?)', array_merge(array($categoryId), $subCategoriesIds));
        return $select;
    }

    public function getOfferSimilars($offer, $rowCount) {
        /* @var $select Zend_Db_Select */
        $select = $this->getDbTable()->selectActiveOffers();
        $select->where('o.category_id = ?', $offer['category_id']);
        $select->where('o.offer_id != ?', $offer['offer_id'])
                ->limitPage(1, $rowCount);
//        d($select->assemble());
        $offers = $select->query()->fetchAll();
        return $offers;
    }

    /**
     *
     * @param type $userId
     * @return type 
     */
    public function getOffersByAuthor($userId) {
        $select = $this->getFullOffers();
        $select->where('o.author_id = ?', $userId);
        return $select;
    }

    protected function getDbTableNameMap() {
        return array(
            self::DB_OFFER => 'Application_Model_DbTable_Offer',
            self::DB_OFFER_ATTRIBUTE => 'Application_Model_DbTable_OfferAttribute',
        );
    }

    protected function getDefaultDbTableName() {
        return self::DB_OFFER;
    }

}
